# -*- coding:utf-8 -*-
"""
@FileName  :strategy.py
@Time      :2022/7/5 11:27
@Author    :fsksf
"""
import json
from typing import Optional, Awaitable

from pyrestful.rest import get, post, put, delete
from pyrestful import mediatypes
from vcat.server.base_handler import BaseResource

from vcat.server.routes import ALL_ROUTES
from vcat.utils.api_util import add_handler
from vcat.server.status_code import make_response, Code
from vcat.server.server import app
from vcat.server import TABLE_METAS, BROKER_METAS


@add_handler
class StrategyAPIResource(BaseResource):

    @get(_path='/api/strategy/classes', _types=[dict],
         _catch_fire=True, _produces=mediatypes.APPLICATION_JSON,
         _consumes=mediatypes.APPLICATION_JSON)
    def strategy_classes(self):
        strategies = app.engine.get_all_strategy_class()
        classes_info = [stra.meta() for stra in strategies]

        return make_response(code=Code.OK, data=classes_info)

    @get(_path='/api/strategy/clsParams', _types=[dict],
         _catch_fire=True, _produces=mediatypes.APPLICATION_JSON,
         _consumes=mediatypes.APPLICATION_JSON)
    def strategy_cls_params(self, name):
        name = name.decode()
        strategy_cls = app.engine.get_strategy_cls_by_name(name)
        data = strategy_cls.get_init_params()

        return make_response(code=Code.OK, data=data)

    @post(_path='/api/strategy/init', _types=[dict],
          _catch_fire=True, _produces=mediatypes.APPLICATION_JSON,
          _consumes=mediatypes.APPLICATION_JSON)
    def add_strategy_instance(self, *args):
        data = args[0]
        cls_name = data.pop('clsName')
        strategy_ins_name = data.pop('name')
        cid_list = data.pop('contract_ids').split(',')
        start_dt = data.pop('start_dt')
        start_dt = start_dt or None
        end_dt = data.pop('end_dt')
        end_dt = end_dt or None
        try:
            app.engine.add_strategy_instance(
                strategy_cls_name=cls_name,
                strategy_ins_name=strategy_ins_name,
                cid_list=cid_list,
                start_dt=start_dt,
                end_dt=end_dt,
                params=data
            )
        except Exception as e:
            return make_response(code=Code.error, data=str(e.with_traceback(e)))
        return make_response(code=Code.OK)